package com.demo.state.machine;

import com.demo.model.ApprovalFile;
import com.demo.state.machine.event.Event;
import com.demo.state.machine.status.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.statemachine.StateMachineSystemConstants;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;

/**
 * 状态机监听器
 * 注解@WithStateMachine的id对应@EnableStateMachineFactory的id
 * 注解@WithStateMachine的name对应@EnableStateMachine的name
 */
@Slf4j
@WithStateMachine(id = StateMachineSystemConstants.DEFAULT_ID_STATEMACHINEFACTORY)
public class StateMachineListener {

    @OnTransition(target = "AUDIT")
    public void save(Message<Event> message) {
        ApprovalFile payload = (ApprovalFile) message.getHeaders().get("file");
        payload.setStatus(Status.AUDIT);
        log.info("number = {}, 草稿状态->待审核", getNumber(message));
    }

    @OnTransition(source = "AUDIT", target = "FINISH")
    public void pass(Message<Event> message) {
        ApprovalFile payload = (ApprovalFile) message.getHeaders().get("file");
        payload.setStatus(Status.FINISH);
        log.info("number = {}, 待审批->审批通过", getNumber(message));
    }

    @OnTransition(source = "AUDIT", target = "DRAFT")
    public void unPass(Message<Event> message) {
        ApprovalFile payload = (ApprovalFile) message.getHeaders().get("file");
        payload.setStatus(Status.DRAFT);
        log.info("number = {}, 待审批->草稿状态", getNumber(message));
    }

    private int getNumber(Message<Event> message) {
        return (int) message.getHeaders().get("number");
    }
}
